package org.marsdonne.audits.resolver;

import graphql.kickstart.tools.GraphQLQueryResolver;
import org.marsdonne.audits.Auth;
import org.marsdonne.audits.Note;
import org.marsdonne.audits.NoteFilters;
import org.marsdonne.audits.repos.NoteRepos;
import org.marsdonne.commons.jpa.FilterSpecSupport;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class NoteQueryResolver implements GraphQLQueryResolver, FilterSpecSupport<Note> {
    @Resource
    private NoteRepos repos;

    public Iterable<Note> getNotes(NoteFilters filters) {
        Specification<Note> spec = null;

        if(filters != null) {
            if(filters.getServiceId() != null)
                spec = by("serviceId", filters.getServiceId());

            if(filters.getLevel() != null) {
                Specification<Note> specPart = by("level", filters.getLevel());
                spec = (spec == null) ? specPart : spec.and(specPart);
            }

            if(filters.getDateLogged() != null) {
                Specification<Note> specPart = by("dateLogged", filters.getDateLogged());
                spec = (spec == null) ? specPart : spec.and(specPart);
            }
        }

        Sort sort = Sort.by("dateLogged").descending();

        if (spec == null)
            return repos.findAll(sort);
        else
            return repos.findAll(spec, sort);
    }
}
